package com.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.util.Xml;

public class DataService {

	public static Map<String, Object> getAttendActivity(String content,int id){
		
		String path;
		try {
			path = "http://www.liaonimei.com/app/getAnswer.do?mq=" + URLEncoder.encode(content, "UTF-8")
					+ "&mf=guest&mt="+id;
			//System.out.println("path=" + path);
			try {
				HttpURLConnection con;
				con = (HttpURLConnection) new URL(path)
						.openConnection();
				con.setConnectTimeout(15000);
				con.setRequestProperty("Charset", "UTF-8");
				con.setRequestMethod("GET");
				try
				{
					int i = con.getResponseCode();
					if (i == 200) {
						InputStream in = con.getInputStream();
						return parseUpdate(in);
					}
				}
				catch (UnknownHostException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			} 
			catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
		return null;
	}

	private static Map<String, Object> parseUpdate(InputStream in) {
		Map<String, Object> map = new HashMap<String, Object>();
		XmlPullParser pullParser = Xml.newPullParser();
		try {
			pullParser.setInput(in, "UTF-8");
			int event = pullParser.getEventType();
			while (event != XmlPullParser.END_DOCUMENT) {

				if (pullParser.getEventType() == XmlPullParser.START_TAG) {
					String tagName = pullParser.getName();
					if (tagName.equals("answer")) {
						map.put("answer", pullParser.nextText());
					} else if (tagName.equals("code")) {
						map.put("code", pullParser.nextText());
					}
				}
				event = pullParser.next();
			}

		} catch (XmlPullParserException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("update map=" + map);
		System.out.println("update map code=" + map.get("code"));
		return map;
	}
}
